<%--
  Created by IntelliJ IDEA.
  User: ZTK
  Date: 2025/6/14
  Time: 00:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
  <title>二手平台 - 购物车</title>
  <link href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/bootstrap-icons.css">
  <style>
    /* 新增的CSS样式 */
    .cart-header, .cart-footer > div {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .btn-settle:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }

    :root {
      --primary-color: #ff5000;
      --secondary-color: #f5f5f5;
    }

    body {
      background-color: #f5f5f5;
      padding-top: 56px;
    }

    .navbar {
      background-color: var(--primary-color);
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .navbar-brand {
      font-weight: bold;
      color: white !important;
    }

    /* 操作消息样式 */
    .action-message {
      position: fixed;
      top: 70px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 1050;
      padding: 10px 20px;
      border-radius: 5px;
      color: white;
      font-weight: bold;
      box-shadow: 0 2px 10px rgba(0,0,0,0.2);
      display: none;
    }

    .action-message.success {
      background-color: #4CAF50;
    }

    .action-message.error {
      background-color: #f44336;
    }

    /* 购物车样式 */
    .cart-header {
      background-color: white;
      padding: 15px;
      font-weight: bold;
      border-bottom: 1px solid #eee;
    }

    .cart-item {
      background-color: white;
      padding: 15px;
      border-bottom: 1px solid #eee;
      display: flex;
    }

    .cart-item-image {
      width: 100px;
      height: 100px;
      object-fit: contain;
      margin-right: 15px;
      border-radius: 5px;
    }

    .cart-item-details {
      flex-grow: 1;
    }

    .cart-item-title {
      font-weight: bold;
      margin-bottom: 5px;
    }

    .cart-item-price {
      color: #ff5000;
      font-weight: bold;
      margin-bottom: 5px;
    }

    .cart-item-subtotal {
      color: #e91e63;
      font-weight: bold;
      margin-bottom: 10px;
      font-size: 1.1rem;
    }

    .cart-item-quantity {
      display: flex;
      align-items: center;
      margin-top: 10px;
    }

    .quantity-btn {
      width: 30px;
      height: 30px;
      border: 1px solid #ddd;
      background: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      font-weight: bold;
    }

    .quantity-input {
      width: 40px;
      height: 30px;
      text-align: center;
      border: 1px solid #ddd;
      border-left: none;
      border-right: none;
    }

    .cart-footer {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: white;
      padding: 10px 15px;
      box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .total-price {
      font-weight: bold;
      color: #ff5000;
      font-size: 1.2rem;
    }

    .btn-settle {
      background-color: #ff5000;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 20px;
      font-weight: bold;
    }

    .empty-cart {
      text-align: center;
      padding: 50px 20px;
    }

    .empty-cart i {
      font-size: 5rem;
      color: #ddd;
      margin-bottom: 20px;
    }

    .empty-cart p {
      color: #888;
      margin-bottom: 20px;
    }

    .cart-checkbox {
      margin-right: 10px;
    }

    .price-value {
      font-weight: bold;
      color: #ff5000;
    }
  </style>
</head>

<body>
<!-- 操作提示消息 -->
<div class="action-message" id="actionMessage"></div>

<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark fixed-top">
  <div class="container">
    <a class="navbar-brand" href="${pageContext.request.contextPath}/product/list">二手平台</a>
    <div class="d-flex flex-grow-1 justify-content-center">
      <div class="text-white fw-bold">购物车</div>
    </div>
    <ul class="navbar-nav">
      <c:choose>
        <c:when test="${not empty sessionScope.currentUser}">
          <li class="nav-item">
            <a class="nav-link" href="#"><i class="bi bi-trash"></i></a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown">
                ${sessionScope.currentUser.username}
            </a>
            <ul class="dropdown-menu dropdown-menu-end">
              <li><a class="dropdown-item" href="${pageContext.request.contextPath}/order/list">我的订单</a></li>
              <li><hr class="dropdown-divider"></li>
              <li><a class="dropdown-item" href="${pageContext.request.contextPath}/user/logout">退出登录</a></li>
            </ul>
          </li>
        </c:when>
        <c:otherwise>
          <li class="nav-item">
            <a class="nav-link" href="${pageContext.request.contextPath}/user/login">登录</a>
          </li>
        </c:otherwise>
      </c:choose>
    </ul>
  </div>
</nav>

<c:choose>
  <c:when test="${not empty cartItems && cartItems.size() > 0}">
    <!-- 购物车商品列表 -->
    <div class="cart-header">
      <input type="checkbox" id="selectAll" class="cart-checkbox">
      <label for="selectAll">全选</label>
    </div>

    <div class="cart-items-container">
      <c:forEach items="${cartItems}" var="item">
        <div class="cart-item" id="cart-item-${item.cartId}">
          <input type="checkbox" class="cart-checkbox item-checkbox" data-cartid="${item.cartId}"
                 data-price="${item.product.price}" data-quantity="${item.quantity}" checked>
          <img src="${item.product.imagePath}" class="cart-item-image" alt="${item.product.name}">
          <div class="cart-item-details">
            <div class="cart-item-title">${item.product.name}</div>

            <!-- 商品单价（隐藏值，用于计算） -->
            <input type="hidden" id="price-val-${item.cartId}" value="${item.product.price}">

            <!-- 显示商品单价 -->
            <div class="cart-item-price">
              单价: ¥<span class="price-value" id="price-${item.cartId}">
                <fmt:formatNumber value="${item.product.price}" pattern="#,##0.00" />
              </span>
            </div>

            <!-- 显示小计金额 -->
            <div class="cart-item-subtotal">
              小计: ¥<span class="price-value" id="subtotal-${item.cartId}">
                <fmt:formatNumber value="${item.product.price * item.quantity}" pattern="#,##0.00" />
              </span>
            </div>

            <div class="cart-item-quantity">
              <button class="quantity-btn"
                      onclick="updateQuantity(${item.cartId}, ${item.quantity-1})">-</button>
              <input type="text" class="quantity-input" value="${item.quantity}"
                     id="quantity-${item.cartId}" readonly>
              <button class="quantity-btn"
                      onclick="updateQuantity(${item.cartId}, ${item.quantity+1})">+</button>
            </div>
            <button class="btn btn-sm btn-danger mt-2"
                    onclick="removeItem(${item.cartId})">删除</button>
          </div>
        </div>
      </c:forEach>
    </div>

    <!-- 底部结算栏 -->
    <div class="cart-footer">
      <div>
        <input type="checkbox" id="footerSelect" class="cart-checkbox">
        <label for="footerSelect">全选</label>
        <div class="total-price">
          合计: ¥<span class="total-price-amount" id="total-amount">
            <c:choose>
              <c:when test="${not empty totalAmount}">
                <fmt:formatNumber value="${totalAmount}" pattern="#,##0.00" />
              </c:when>
              <c:otherwise>
                0.00
              </c:otherwise>
            </c:choose>
          </span>
        </div>
      </div>
      <button class="btn-settle" id="settle-btn" onclick="checkout()">
        结算(<span id="selected-count">${cartItems.size()}</span>)
      </button>
    </div>

  </c:when>
  <c:otherwise>
    <!-- 空购物车 -->
    <div class="empty-cart">
      <i class="bi bi-cart"></i>
      <p>购物车空空如也，去逛逛吧</p>
      <a href="${pageContext.request.contextPath}/product/list" class="btn btn-outline-primary">去逛逛</a>
    </div>
  </c:otherwise>
</c:choose>

<script src="${pageContext.request.contextPath}/resources/js/popper.min.js"></script>
<script src="${pageContext.request.contextPath}/resources/js/bootstrap.min.js"></script>
<script src="${pageContext.request.contextPath}/resources/js/jquery-3.6.0.min.js"></script>
<script>

  function setupSelectAll() {

    $('#selectAll, #footerSelect').on('change', function() {
      const isChecked = $(this).prop('checked');
      $('.item-checkbox').prop('checked', isChecked);
      updateTotalAndButton();

      $('#selectAll, #footerSelect').prop('checked', isChecked);
    });

    $('.cart-items-container').on('change', '.item-checkbox', function() {
      updateSelectAllState();
      updateTotalAndButton();
    });
  }

  function updateSelectAllState() {
    const totalItems = $('.item-checkbox').length;
    const checkedItems = $('.item-checkbox:checked').length;

    if (checkedItems === 0) {
      $('#selectAll, #footerSelect').prop('checked', false).prop('indeterminate', false);
    } else if (checkedItems === totalItems) {
      $('#selectAll, #footerSelect').prop('checked', true).prop('indeterminate', false);
    } else {
      $('#selectAll, #footerSelect').prop('checked', false).prop('indeterminate', true);
    }
  }

  function updateTotalAndButton() {
    updateSelectedCount();
    updateTotalAmount();
    updateButtonState();
  }

  function updateSelectedCount() {
    const selectedCount = $('.item-checkbox:checked').length;
    $('#selected-count').text(selectedCount);
  }

  function updateTotalAmount() {
    let total = 0;

    $('.item-checkbox:checked').each(function() {
      const price = parseFloat($(this).data('price'));
      const quantity = parseInt($(this).data('quantity'));
      total += price * quantity;
    });

    $('#total-amount').text(total.toFixed(2));
  }

  function updateButtonState() {
    const selectedCount = $('.item-checkbox:checked').length;
    const settleButton = $('#settle-btn');

    if (selectedCount === 0) {
      settleButton.prop('disabled', true);
    } else {
      settleButton.prop('disabled', false);
    }
  }

  function updateQuantity(cartId, newQuantity) {
    if (newQuantity < 1) newQuantity = 1;

    const quantityInput = $(`#quantity-${cartId}`);
    quantityInput.prop('disabled', true).val('更新中...');

    $.ajax({
      type: "POST",
      url: "${pageContext.request.contextPath}/cart/update",
      data: {
        cartId: cartId,
        quantity: newQuantity
      },
      success: function(response) {
        if (response.success) {

          const checkbox = $(`.item-checkbox[data-cartid="${cartId}"]`);
          checkbox.data('quantity', newQuantity);

          const price = parseFloat(checkbox.data('price'));
          const subtotal = price * newQuantity;
          $(`#subtotal-${cartId}`).text(subtotal.toFixed(2));

          updateTotalAmount();
          location.reload();
        } else {

          quantityInput.val(quantityInput.data('old-value')).prop('disabled', false);
          showMessage(response.message || '更新失败', true);
        }
      },
      error: function(xhr) {

        quantityInput.val(quantityInput.data('old-value')).prop('disabled', false);
        showMessage('更新失败: ' + xhr.status + ' - ' + xhr.statusText, true);
      }
    });
  }

  function removeItem(cartId) {
    if (!confirm('确定要删除这个商品吗？')) return;

    const cartItem = $(`#cart-item-${cartId}`);
    cartItem.css('opacity', '0.5').find('button').prop('disabled', true);

    $.ajax({
      type: "POST",
      url: "${pageContext.request.contextPath}/cart/remove",
      data: {
        cartId: cartId
      },
      success: function(response) {
        if (response.success) {

          location.reload();
        } else {
          cartItem.css('opacity', '').find('button').prop('disabled', false);
          showMessage(response.message || '删除失败', true);
        }
      },
      error: function(xhr) {
        cartItem.css('opacity', '').find('button').prop('disabled', false);
        showMessage('删除失败: ' + xhr.status + ' - ' + xhr.statusText, true);
      }
    });
  }

  function checkout() {

    const selectedItems = [];
    $('.item-checkbox:checked').each(function() {
      selectedItems.push($(this).data('cartid'));
    });

    if (selectedItems.length === 0) {
      showMessage('请至少选择一件商品', true);
      return;
    }

    window.location.href = "${pageContext.request.contextPath}/order/create?cartIds=" + selectedItems.join(',');
  }

  function showMessage(message, isError = false) {
    const messageDiv = $('#actionMessage');
    messageDiv.text(message);
    messageDiv.removeClass('error success');
    messageDiv.addClass(isError ? 'error' : 'success');
    messageDiv.show();

    setTimeout(() => {
      messageDiv.hide();
    }, 3000);
  }

  $(document).ready(function() {

    $('.quantity-input').each(function() {
      $(this).data('old-value', $(this).val());
    });

    setupSelectAll();

    updateTotalAndButton();

    $('#selectAll, #footerSelect').prop('checked', true);

    updateButtonState();
  });
</script>
</body>
</html>